<template>
	<view class="add-goods-container">
		<!-- 添加PLoader组件 -->
		<p-loader :loading="loading" loadingText="上传中..." backgroundColor="rgba(255, 255, 255, 0.9)"></p-loader>
		
		<view class="goods-form">
			<view class="form-title">商品基本信息</view>

			<view class="form-item">
				<text class="label required">商品名称</text>
				<uv-input v-model="formData.name" placeholder="请输入商品名称" border="surround"
					:customStyle="{ backgroundColor: '#fafafa' }"></uv-input>
			</view>

			<view class="form-item">
				<text class="label required">商品分类</text>
				<view class="category-picker" @tap="showCategoryPicker">
					<text :class="['picker-text', formData.category ? '' : 'placeholder']">
						{{ formData.category || '请选择商品分类' }}
					</text>
					<text class="iconfont icon-arrow-right"></text>
				</view>
			</view>

			<view class="form-item">
				<text class="label required">商品库存</text>
				<uv-number-box v-model="formData.stock" :min="1" :max="999999" :step="1" :integer="true"
					:buttonSize="36" :bgColor="'#f5f5f5'" :color="'#333333'" :iconStyle="{ color: '#666666' }"
					:customStyle="{ borderRadius: '8rpx' }"></uv-number-box>
				<text class="sub-label">库存必须大于0</text>
			</view>

			<view class="form-item">
				<text class="label required">售后联系号码</text>
				<uv-input v-model="formData.servicePhone" type="number" placeholder="请输入售后联系电话" border="surround"
					:customStyle="{ backgroundColor: '#fafafa' }" :maxlength="11"></uv-input>
			</view>

			<view class="form-item">
				<text class="label">商品介绍</text>
				<uv-textarea v-model="formData.description" placeholder="请输入商品介绍" border="surround"
					:customStyle="{ backgroundColor: '#fafafa' }" height="200"></uv-textarea>
			</view>

			<view class="form-item">
				<text class="label required">商品主图</text>
				<text class="sub-label">建议尺寸800x800px，最多上传3张，第一张将作为商品主图</text>
				<view class="upload-list">
					<view class="upload-item" v-for="(img, index) in formData.mainImages" :key="index">
						<image :src="img" mode="aspectFill"></image>
						<text class="delete-btn" @tap.stop="deleteMainImage(index)">×</text>
						<text class="image-index">{{ index + 1 }}</text>
					</view>
					<view class="upload-btn" @tap="chooseImage('main')" v-if="formData.mainImages.length < 3">
						<text class="iconfont icon-add"></text>
						<text class="upload-text">上传图片</text>
					</view>
				</view>
			</view>

			<view class="form-item">
				<text class="label required">详情图片</text>
				<text class="sub-label">建议尺寸宽度750px，必须上传1-6张图片</text>
				<view class="upload-list">
					<view class="upload-item" v-for="(img, index) in formData.detailImages" :key="index">
						<image :src="img" mode="aspectFill"></image>
						<text class="delete-btn" @tap.stop="deleteDetailImage(index)">×</text>
						<text class="image-index">{{ index + 1 }}</text>
					</view>
					<view class="upload-btn" @tap="chooseImage('detail')" v-if="formData.detailImages.length < 6">
						<text class="iconfont icon-add"></text>
						<text class="upload-text">上传图片</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 价格信息表单 -->
		<view class="goods-form" v-if="formData.category">
			<view class="form-title">价格设置</view>

			<!-- 所有类型都需要的价格输入 -->
			<view class="form-item">
				<text class="label required">商品价格</text>
				<uv-input v-model="formData.price" type="number" :precision="2" placeholder="请输入商品价格"
					border="surround" :customStyle="{ backgroundColor: '#fafafa' }" :maxlength="10"></uv-input>
			</view>

			<!-- 添加邮费设置 -->
			<view class="form-item">
				<text class="label required">配送方式</text>
				<view class="radio-group">
					<view class="radio-item" :class="{ active: formData.isFreeShipping }" 
						@tap="selectShippingType(true)">
						<text>包邮</text>
					</view>
					<view class="radio-item" :class="{ active: !formData.isFreeShipping }" 
						@tap="selectShippingType(false)">
						<text>收费</text>
					</view>
				</view>
			</view>

			<!-- 邮费输入框，仅在选择收费时显示 -->
			<view class="form-item" v-if="!formData.isFreeShipping">
				<text class="label required">邮费金额</text>
				<uv-input v-model="formData.shippingFee" type="number" :precision="2" 
					placeholder="请输入邮费金额" border="surround" 
					:customStyle="{ backgroundColor: '#fafafa' }" 
					:maxlength="10"
					@blur="handleInputBlur('shippingFee')"></uv-input>
			</view>

			<!-- 礼品卡/券专区 -->
			<template v-if="isGiftCategory">
				<view class="form-item">
					<text class="label required">所需{{ isGiftCard ? '礼品卡' : '礼品券' }}数量</text>
					<uv-input v-model="formData.gift_num" type="number" placeholder="请输入数量" border="surround"
						:customStyle="{ backgroundColor: '#fafafa' }" :maxlength="5"></uv-input>
				</view>
			</template>

			<!-- 普通商品支付方式选择 -->
			<template v-else>
				<view class="form-item">
					<text class="label required">支付方式</text>
					<view class="radio-group">
						<view class="radio-item" :class="{ active: formData.payment_type === 1 }"
							@tap="selectPaymentType(1)">
							<text>仅现金</text>
						</view>
						<view class="radio-item" :class="{ active: formData.payment_type === 2 }"
							@tap="selectPaymentType(2)">
							<text>仅积分</text>
						</view>
						<view class="radio-item" :class="{ active: formData.payment_type === 3 }"
							@tap="selectPaymentType(3)">
							<text>积分混合</text>
						</view>
					</view>
				</view>

				<!-- 积分相关设置 -->
				<template v-if="formData.payment_type === 2 || formData.payment_type === 3">
					<view class="form-item">
						<text class="label required">积分兑换比例</text>
						<uv-input v-model="formData.pointsRatio" type="number" :precision="2" placeholder="请输入1元对应的积分数"
							border="surround" :customStyle="{ backgroundColor: '#fafafa' }" :maxlength="10"></uv-input>
					</view>
				</template>

				<!-- 积分混合支付额外设置 -->
				<template v-if="formData.payment_type === 3">
					<view class="form-item">
						<text class="label required">积分可抵扣金额</text>
						<uv-input v-model="formData.points_deduction" type="number" :precision="2"
							placeholder="请输入积分可抵扣的金额" border="surround" :customStyle="{ backgroundColor: '#fafafa' }"
							:maxlength="10"></uv-input>
					</view>
					<view class="form-item">
						<text class="label">支付明细</text>
						<view class="payment-detail">
							<view class="detail-item">
								<text>现金支付：</text>
								<text class="value">{{ calculatedCashPrice || '-' }} 元</text>
							</view>
							<view class="detail-item">
								<text>积分支付：</text>
								<text class="value">{{ calculatedMixPoints || '-' }} 积分</text>
							</view>
							<view class="detail-item" v-if="showDeductionError">
								<text class="error">抵扣金额不能大于商品价格</text>
							</view>
						</view>
					</view>
				</template>
			</template>
		</view>

		<!-- 使用 uv-picker 替换原有的分类选择器 -->
		<uv-picker ref="uvPicker" :columns="[category]" keyName="name" @confirm="confirmCategory"
			@cancel="closeCategoryPicker" :defaultIndex="categoryIndex" confirmColor="#3c9cff" title="选择分类"></uv-picker>

		<uv-picker ref="paymentPicker" :columns="[paymentTypes]" keyName="label" @confirm="confirmPaymentType"
			@cancel="closePaymentPicker" confirmColor="#3c9cff" title="选择支付方式"></uv-picker>

		<view class="submit-bar">
			<view class="submit-btn" @tap="handleSubmit">
				<text>提交审核</text>
			</view>
		</view>
	</view>
</template>

<script>
import PLoader from '@/components/PLoader/PLoader.vue'

export default {
	components: {
		PLoader
	},

	data() {
		return {
			category: [],
			categoryIndex: [0],
			paymentTypes: [
				{ label: '现金支付', value: 1 },
				{ label: '积分支付', value: 2 },
				{ label: '积分+现金', value: 3 },
				{ label: '礼品卡', value: 4 },
				{ label: '礼品券', value: 5 }
			],
			formData: {
				name: '',
				category: '',
				categoryId: '',
				stock: 1,
				servicePhone: '',
				description: '',
				mainImages: [],
				detailImages: [],
				payment_type: 1,
				price: '',
				pointsRatio: '',
				points_deduction: '',
				gift_num: '',
				isFreeShipping: true, // 默认包邮
				shippingFee: '', // 邮费金额
			},
			uploadedImages: [],
			loading: false
		}
	},

	computed: {
		isGiftCategory() {
			return this.formData.category?.includes('礼品');
		},

		isGiftCard() {
			return this.formData.category?.includes('礼品卡');
		},

		calculatedPoints() {
			if (!this.formData.price || !this.formData.pointsRatio) return 0;
			return (parseFloat(this.formData.price) * parseFloat(this.formData.pointsRatio)).toFixed(0);
		},

		calculatedCashPrice() {
			if (!this.formData.price || !this.formData.points_deduction) return 0;
			const price = parseFloat(this.formData.price);
			const deduction = parseFloat(this.formData.points_deduction);
			return deduction > price ? 0 : (price - deduction).toFixed(2);
		},

		calculatedMixPoints() {
			if (!this.formData.points_deduction || !this.formData.pointsRatio) return 0;
			const deduction = parseFloat(this.formData.points_deduction);
			const ratio = parseFloat(this.formData.pointsRatio);
			return (deduction * ratio).toFixed(0);
		},

		showDeductionError() {
			if (!this.formData.price || !this.formData.points_deduction) return false;
			const price = parseFloat(this.formData.price);
			const deduction = parseFloat(this.formData.points_deduction);
			return deduction > price;
		}
	},

	watch: {
		'formData.category'(newVal) {
			this.resetPriceForm();
		},

		'formData.price'(newVal) {
			if (newVal === '') return;
			this.formData.price = this.formatNumber(newVal);
		},

		'formData.points_deduction'(newVal) {
			if (newVal === '') return;
			this.formData.points_deduction = this.formatNumber(newVal);

			if (this.showDeductionError) {
				uni.showToast({
					title: '抵扣金额不能大于商品价格',
					icon: 'none'
				});
			}
		},

		'formData.pointsRatio'(newVal) {
			if (newVal === '') return;
			this.formData.pointsRatio = this.formatNumber(newVal);
		}
	},

	methods: {
		// 统一处理错误
		handleError(e, defaultMsg) {
			uni.showToast({
				title: e.msg || defaultMsg,
				icon: 'none'
			})
		},

		async fetchCategory() {
			try {
				const data = await this.$http.get('/mall/category/all');
				if (data) {
					this.category = data;
				}
			} catch (e) {
				this.handleError(e, '无法加载分类信息')
			}
		},

		// 上传图片
		async uploadImage(filePath, type) {
			try {
				const baseUrl = this.$config.baseUrl;
				const res = await uni.uploadFile({
					url: baseUrl + '/mall/goods/image',
					filePath: filePath,
					name: 'file',
					header: {
						'Authorization': uni.getStorageSync('token')
					},
					formData: {
						type: type
					}
				});

				if (res.statusCode === 200) {
					const data = JSON.parse(res.data);
					if (data.code === 200) {
						this.uploadedImages.push(data.data);
						return data.data;
					} else {
						throw new Error(data.msg || '上传失败');
					}
				}
				throw new Error('上传失败');
			} catch (e) {
				this.handleError(e, '图片上传失败')
				throw e;
			}
		},

		// 选择并上传图片
		async chooseImage(type) {
			try {
				const res = await uni.chooseImage({
					count: type === 'main' ?
						3 - this.formData.mainImages.length :
						6 - this.formData.detailImages.length,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera']
				});

				// 显示PLoader
				this.loading = true;

				try {
					// 上传所有选中的图片
					const uploadTasks = res.tempFilePaths.map(path =>
						this.uploadImage(path, type)
					);

					const urls = await Promise.all(uploadTasks);

					// 添加到对应的图片数组
					if (type === 'main') {
						this.formData.mainImages.push(...urls);
					} else {
						this.formData.detailImages.push(...urls);
					}
				} catch (e) {
					console.error('部分图片上传失败:', e);
					uni.showToast({
						title: '部分图片上传失败',
						icon: 'none'
					});
				}
			} catch (e) {
			} finally {
				// 隐藏PLoader
				this.loading = false;
			}
		},

		// 删除主图
		async deleteMainImage(index) {
			const imageUrl = this.formData.mainImages[index];
			try {
				const encodedUrl = encodeURIComponent(imageUrl);
				const res = await this.$http.post(`/mall/goods/delImage?url=${encodedUrl}`);
				
				if (res) {
					this.formData.mainImages.splice(index, 1);
					const uploadedIndex = this.uploadedImages.indexOf(imageUrl);
					if (uploadedIndex > -1) {
						this.uploadedImages.splice(uploadedIndex, 1);
					}
				}
			} catch (e) {
				this.handleError(e, '删除图片失败')
			}
		},

		// 删除详情图
		async deleteDetailImage(index) {
			const imageUrl = this.formData.detailImages[index];
			try {
				const encodedUrl = encodeURIComponent(imageUrl);
				const res = await this.$http.post(`/mall/goods/delImage?url=${encodedUrl}`);
				
				if (res) {
					this.formData.detailImages.splice(index, 1);
					const uploadedIndex = this.uploadedImages.indexOf(imageUrl);
					if (uploadedIndex > -1) {
						this.uploadedImages.splice(uploadedIndex, 1);
					}
				}
			} catch (e) {
				this.handleError(e, '删除图片失败')
			}
		},

		// 清理所有已上传的图片
		async cleanUploadedImages() {
			// 先清除表单中的图片数据
			this.formData.mainImages = [];
			this.formData.detailImages = [];
			
			// 再清理服务端的图片
			const promises = this.uploadedImages.map(url => {
				const encodedUrl = encodeURIComponent(url);
				return this.$http.post(`/mall/goods/delImage?url=${encodedUrl}`);
			});
			
			try {
				await Promise.all(promises);
				this.uploadedImages = [];
			} catch (e) {
				console.error('清理图片失败:', e);
				this.handleError(e, '清理图片失败')
			} finally {
				// 确保uploadedImages被清空
				this.uploadedImages = [];
			}
		},

		showCategoryPicker() {
			this.$refs.uvPicker.open();
		},

		closeCategoryPicker() {
			this.$refs.uvPicker.close();
		},

		confirmCategory(e) {
			const selectedCategory = e.value[0];
			this.formData.category = selectedCategory.name;
			this.formData.categoryId = selectedCategory.id;
			
			// 根据分类自动设置支付类型
			if (selectedCategory.name.includes('礼品卡')) {
				this.formData.payment_type = 4;
			} else if (selectedCategory.name.includes('礼品券')) {
				this.formData.payment_type = 5;
			} else {
				this.formData.payment_type = 1; // 默认为现金支付
			}
		},

		showPaymentPicker() {
			this.$refs.paymentPicker.open();
		},

		closePaymentPicker() {
			this.$refs.paymentPicker.close();
		},

		confirmPaymentType(e) {
			const selected = e.value[0];
			this.formData.payment_type = selected.value;
			this.clearPriceFields();
		},

		clearPriceFields() {
			this.formData.price = '';
			this.formData.points = '';
			this.formData.points_cash_price = '';
			this.formData.points_cash_points = '';
			this.formData.gift_card_num = '';
			this.formData.gift_voucher_num = '';
		},

		getPaymentTypeText() {
			if (!this.formData.payment_type) return '';
			const found = this.paymentTypes.find(item => item.value === this.formData.payment_type);
			return found ? found.label : '';
		},

		resetPriceForm() {
			this.formData.price = '';
			this.formData.pointsRatio = '';
			this.formData.points_deduction = '';
			this.formData.gift_num = '';
			this.formData.isFreeShipping = true;
			this.formData.shippingFee = '';
		},

		selectPaymentType(type) {
			this.formData.payment_type = type;
			this.formData.pointsRatio = '';
			this.formData.points_deduction = '';
		},

		formatNumber(value) {
			value = value.toString().replace(/[^\d.]/g, '');

			const parts = value.split('.');
			if (parts.length > 2) {
				value = parts[0] + '.' + parts.slice(1).join('');
			}

			if (parts.length === 2 && parts[1].length > 2) {
				value = parseFloat(value).toFixed(2);
			}

			if (!value.includes('.')) {
				return value;
			}

			return parseFloat(value).toFixed(2);
		},

		handleInputBlur(field) {
			if (this.formData[field] === '') return;

			this.formData[field] = parseFloat(this.formData[field]).toFixed(2);
		},

		handleGiftNumInput(value) {
			this.formData.gift_num = value;
		},

		handlePriceInput(value) {
			this.formData[value.field] = value.value;
		},

		// 选择配送方式
		selectShippingType(isFree) {
			this.formData.isFreeShipping = isFree;
			if (isFree) {
				this.formData.shippingFee = '';
			}
		},

		// 提交表单
		async handleSubmit() {
			// 表单验证
			if (!this.formData.name) {
				return uni.showToast({
					title: '请输入商品名称',
					icon: 'none'
				});
			}
			if (!this.formData.categoryId) {
				return uni.showToast({
					title: '请选择商品分类',
					icon: 'none'
				});
			}
			if (!this.formData.stock || parseInt(this.formData.stock) < 1) {
				return uni.showToast({
					title: '库存必须大于0',
					icon: 'none'
				});
			}
			if (!this.formData.servicePhone) {
				return uni.showToast({
					title: '请输入售后联系号码',
					icon: 'none'
				});
			}
			// 验证手机号格式
			if (!/^1[3-9]\d{9}$/.test(this.formData.servicePhone)) {
				return uni.showToast({
					title: '请输入正确的手机号',
					icon: 'none'
				});
			}
			if (this.formData.mainImages.length === 0) {
				return uni.showToast({
					title: '请上传商品主图',
					icon: 'none'
				});
			}
			if (this.formData.mainImages.length > 3) {
				return uni.showToast({
					title: '主图最多上传3张',
					icon: 'none'
				});
			}
			if (this.formData.detailImages.length === 0) {
				return uni.showToast({
					title: '请上传商品详情图',
					icon: 'none'
				});
			}
			if (this.formData.detailImages.length > 6) {
				return uni.showToast({
					title: '详情图最多上传6张',
					icon: 'none'
				});
			}

			// 价格验证 - 所有类型都需要
			if (!this.formData.price) {
				return uni.showToast({
					title: '请输入商品价格',
					icon: 'none'
				});
			}

			// 添加邮费验证
			if (!this.formData.isFreeShipping) {
				if (!this.formData.shippingFee) {
					return uni.showToast({
						title: '请输入邮费金额',
						icon: 'none'
					});
				}
				if (parseFloat(this.formData.shippingFee) <= 0) {
					return uni.showToast({
						title: '邮费金额必须大于0',
						icon: 'none'
					});
				}
			}

			// 构建提交数据
			const submitData = {
				name: this.formData.name,
				categoryId: this.formData.categoryId,
				category: this.formData.category,
				stock: parseInt(this.formData.stock),
				servicePhone: this.formData.servicePhone,
				description: this.formData.description,
				mainImages: this.formData.mainImages,
				detailImages: this.formData.detailImages,
				price: parseFloat(this.formData.price),
				paymentType: this.formData.payment_type,
			};

			// 如果不是包邮，才添加运费字段
			if (!this.formData.isFreeShipping) {
				submitData.shippingFee = parseFloat(this.formData.shippingFee);
			}

			// 根据支付方式添加相应字段
			if (this.isGiftCategory) {
				if (!this.formData.gift_num) {
					return uni.showToast({
						title: '请输入礼品数量',
						icon: 'none'
					});
				}
				// 根据分类设置正确的支付类型
				submitData.paymentType = this.formData.category.includes('礼品卡') ? 4 : 5;
				if (submitData.paymentType === 4) {
					submitData.giftCardNum = parseInt(this.formData.gift_num);
				} else {
					submitData.giftVoucherNum = parseInt(this.formData.gift_num);
				}
			} else {
				switch (submitData.paymentType) { // 注意这里使用 submitData.paymentType
					case 1: // 现金
						if (!this.formData.price) {
							return uni.showToast({
								title: '请输入商品价格',
								icon: 'none'
							});
						}
						submitData.price = parseFloat(this.formData.price);
						break;
					case 2: // 积分
						if (!this.formData.pointsRatio) {
							return uni.showToast({
								title: '请输入积分兑换比例',
								icon: 'none'
							});
						}
						submitData.pointsRatio = parseFloat(this.formData.pointsRatio);
						break;
					case 3: // 积分+现金
						if (!this.formData.pointsRatio || !this.formData.points_deduction) {
							return uni.showToast({
								title: '请完善积分混合支付信息',
								icon: 'none'
							});
						}
						submitData.pointsRatio = parseFloat(this.formData.pointsRatio);
						submitData.pointsDeduction = parseFloat(this.formData.points_deduction);
						break;
				}
			}

			try {
				this.loading = true;
				const res = await this.$http.post('/mall/goods/add', submitData);

				if (res) {
					this.uploadedImages = [];
					uni.showToast({
						title: '提交成功',
						icon: 'success'
					});
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				}
			} catch (e) {
				console.error('提交失败:', e);
				await this.cleanUploadedImages();
				this.handleError(e, '提交失败')
			} finally {
				this.loading = false;
			}
		}
	},

	onLoad() {
		this.fetchCategory();
	},

	onUnload() {
		// 如果有未提交的图片，进行清理
		if (this.uploadedImages.length > 0) {
			this.cleanUploadedImages();
		}
	}

}
</script>

<style lang="scss" scoped>
@import 'add_goods.scss';

.radio-group {
	display: flex;
	gap: 20rpx;
	margin-top: 10rpx;
	
	.radio-item {
		flex: 1;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #f5f5f5;
		border-radius: 8rpx;
		font-size: 28rpx;
		color: #666;
		
		&.active {
			background-color: #ecf5ff;
			color: #3c9cff;
			border: 2rpx solid #3c9cff;
		}
	}
}
</style>